<?php
namespace Apps\Manage\Controllers;
use Phalcon\Db\RawValue;
use Phalcon\Mvc\View;
use PhalconPlus\Common\ResponseResult;
use PhalconPlus\Common\ResponseResultStatus;
use Apps\Common\Libs\UploadPic;
use Apps\Common\Models\CosBeautyCanon;
use Apps\Common\Libs\PicUrl;
use Apps\Common\Models\SysOpenCity;
use Apps\Common\Models\CosPointCanon;
use Apps\Common\Libs\Jpush;
/**
 * 美粒宝典
 * @author     chenxiaolin
 * @date        2016年1月19日
 * @version     2.0.0
 * @copyright   Copyright 2016 meelier.com
 */
class BeautycanonController extends BaseController{
	public function initialize() {
		parent::initialize ();
		$this->setMainNav ( 'beautycanon' );
	}
	public function indexAction() {
		$this->response->redirect ( 'beautycanon/list' );
	}
	/**
	 * 开通城市列表
	 * @date: 2016年1月4日 
	 * @author: chenxiaolin
	 */
	private function openCityList()
	{
		return SysOpenCity::find();
	}
	/**
	 * 美粒宝典列表
	 * @date: 2016年1月4日 
	 * @author: chenxiaolin
	 */
	public function listAction(){
		$this->setLeftNav ( 'list' );
		$req = $this->request;
		$page = intval($req->getQuery('page', null, 1));
		$page = $page > 0 ? $page : 1;
		$limit = $this->pageNavLimit;
		$offset = $limit * ($page - 1);
		$title = $req->getQuery('title');
		$filterCity = intval ( $req->getQuery ( 'filterCity', null, - 10000 ) );
		
		if($title!=''){
			$wherearr[]="title like '%".$title."%'";
			$this->view->setVar("title",$title);
		}
	   if ($filterCity > - 10000) {
			$wherearr[]="Apps\Common\Models\CosBeautyCanon.city_id = $filterCity";
		}
		$state = $req -> getQuery('state');
		$this->view->setVar("state",$state);
		//$wherearr[]="state <> 3";
		$wherearr[]="state = $state";
		$where = implode(" and ",$wherearr);
		$query=CosBeautyCanon::query();
		$total=CosBeautyCanon::count(['conditions'=>$where]);
		$list = $query
		     -> columns([
		        'Apps\Common\Models\CosBeautyCanon.id',
		        'Apps\Common\Models\CosBeautyCanon.title',
		        'Apps\Common\Models\CosBeautyCanon.img_url',
		        'soc.city_name',
		        'Apps\Common\Models\CosBeautyCanon.fit',
		        'Apps\Common\Models\CosBeautyCanon.assist',
		        'Apps\Common\Models\CosBeautyCanon.state',
		        'Apps\Common\Models\CosBeautyCanon.settime',
		        'Apps\Common\Models\CosBeautyCanon.city_id',
		        ]) 
			->leftJoin ( 'Apps\Common\Models\SysOpenCity', 'soc.city_id=Apps\Common\Models\CosBeautyCanon.city_id', 'soc' )
			->where($where)
			->orderBy('Apps\Common\Models\CosBeautyCanon.settime DESC')
			->limit($limit, $offset)
			->execute()
			->toArray();
		//封面图片地址处理
		foreach ($list as $k=>$v){
			$list[$k]['img_url']=PicUrl::BeautyParlorPic($list[$k]['img_url'], $this->getDi());
		}
		
		$this->view->setVar("total",$total);
		$this->view->setVar("limit",$limit);
		$this->view->setVar("page",$page);
		$this->view->setVar("list",$list);
		$this->view->setVar("filterCity",$filterCity);
		$this->view->setVar ( 'openCity', SysOpenCity::find ('city_state = 1') );
	}
	/**
	 * 首页推荐美粒宝典列表1.0版本
	 * @date: 2016年1月4日 
	 * @author: chenxiaolin
	 */
	public function homelistAction(){
		$this->setLeftNav ( 'homelist' );
		$req=$this->request;
		$page = intval($req->getQuery('page', null, 1));
		$page = $page > 0 ? $page : 1;
		$limit = $this->pageNavLimit;
		$offset = $limit * ($page - 1);
		if($req->getQuery("cityid")){
			$wherearr[]="Apps\Common\Models\CosPointCanon.open_city_id = ".$req->getQuery("cityid");
			$this->view->setVar("cityid",$req->getQuery("cityid"));
		}
		$wherearr[]="c.state <> 3";
		$where=implode(" and ",$wherearr);
		$list=CosPointCanon::query()
			->columns(['c.img_url',
				'c.title',
				'c.id',
				'c.assist',
				'Apps\Common\Models\CosPointCanon.sort as sort',
				'Apps\Common\Models\CosPointCanon.open_city_id as cityid'])
			->leftJoin("Apps\Common\Models\CosBeautyCanon",'Apps\Common\Models\CosPointCanon.canon_id = c.id','c')
			->where($where)
			->orderBy("Apps\Common\Models\CosPointCanon.open_city_id desc")
			->limit($limit, $offset)
			->execute()->toArray();
		foreach ($list as $k=>$v){
			$list[$k]['img_url']="http://img.meelier.com/".$list[$k]['img_url'];
			$list[$k]['city_name']=SysOpenCity::findFirst("city_id = ".$list[$k]['cityid'])->toArray();
		}
		$this->view->setVar("total",count($list));
		$this->view->setVar("limit",$limit);
		$this->view->setVar("page",$page);
		$this->view->setVar("list",$list);
		$this->view->setVar('openCity', $this->openCityList());
	}
	/**
	 * 修改美粒宝典
	 * @date: 2016年1月4日 
	 * @author: chenxiaolin
	 */
	public function editAction(){
	    $this->setLeftNav ('edit');
		$req = $this->request;
		if(!$req->isPost()){
			$id=$req->getQuery("id");
			$info=CosBeautyCanon::findFirst("id = $id")->toArray();
			$info['img_url']=PicUrl::BeautyParlorPic($info['img_url'],$this->getDi());
			$this->view->setVar("info",$info);
			$this->view->setVar("action",'/beautycanon/edit');
			$this->view->setVar ( 'openCity', SysOpenCity::find () );
			//$this->view->pick("beautycanon/edit");
			return;
		}
		$response = new ResponseResult();
		$response->callback = $req->getPost('callback', null, 'parent.setFormResult');
		$response->callbackJavascriptTag = true;
		$id=$req->getPost("id");
		$query=new CosBeautyCanon();
		$model=$query->findFirst("id = $id");
		//修改封面
		if($_FILES['bp_cover']['name']!=''){
			$uploadFile = new UploadPic();
			$uploadFile->request = $req;
			$cover = $uploadFile->beautyParlorCover();
			if($cover == false || !is_array($cover) || count($cover) == 0 || $cover[0] == false) {
				if($_FILES['bp_cover']['error'] == 1) {
					$response->sendError(ResponseResultStatus::UPLOAD_FILE_ERROR,'封面大小超过了1M！');
				} else {
					$response->sendError(ResponseResultStatus::UPLOAD_FILE_ERROR,'封面必须上传！');
				}
				return;
			}
			$model->img_url=$cover[0];
		}
		$title=$req->getPost("title");
		$content=$req->getPost("content");
		$fit = $req->getPost("fit");
		$assist = $req->getPost("assist");
		$summary = $req -> getPost('summary');
		$model->content=$content;
		$model->title=$title;
		$model -> fit = $fit;
		$model -> assist = $assist;
		$model -> summary = $summary;
		//2.0.1需求：编辑美粒宝典后为“待发布”状态
		$model->state = 2;
		
		$status=$model->save();
		$response->sendResult('ok');
        return $response;
	}
	/**
	 * 添加美粒宝典
	 * @date: 2016年1月4日 
	 * @author: chenxiaolin
	 */
	public function addAction(){
	    $this->setLeftNav ( 'add' );
		$req = $this->request;
		if(!$req->isPost()) {
		    $this->view->setVar('openCity', SysOpenCity::find('city_state = 1'));
			$this->view->setVar("action",'/beautycanon/add');
			return;
		}
		$response = new ResponseResult();
		$response->callback = $req->getPost('callback', null, 'parent.setFormResult');
		$response->callbackJavascriptTag = true;
		$uploadFile = new UploadPic();
		$uploadFile->request = $req;
		$cover = $uploadFile->beautyParlorCover();
		//保存封面图片
		if($cover == false || !is_array($cover) || count($cover) == 0 || $cover[0] == false) {
			if($_FILES['bp_cover']['error'] == 1) {
				$response->sendError(ResponseResultStatus::UPLOAD_FILE_ERROR,'封面大小超过了1M！');
			} else {
				$response->sendError(ResponseResultStatus::UPLOAD_FILE_ERROR,'封面必须上传！');
			}
			return;
		}
		$title = $req->getPost("title");
		$content = $req->getPost("content");
		$fit = $req->getPost("fit");
		$assist = $req->getPost("assist");
		$city = $req->getPost("city");
		$summary = $req -> getPost('summary');
		$url = $cover[0];
		//2.0.1需求：添加美粒宝典后为“待发布”状态
		$state = 2;
		//循环添加数据
		foreach ($city as $k => $v){
		    $beautyCanon = new CosBeautyCanon();
		    $beautyCanon -> content = $content;
		    $beautyCanon -> img_url = $url;
		    $beautyCanon -> title = $title;
		    $beautyCanon -> state = $state;
		    $beautyCanon -> fit = $fit;
		    $beautyCanon -> assist = $assist;
		    $beautyCanon -> settime = date("Y-m-d H:i:s");
		    $beautyCanon -> summary = $summary;
		    $beautyCanon -> city_id = $v;
		    $status = $beautyCanon -> save();
		    //添加数据失败
		    if($status == false) {
		        $this->databaseErrorLog($status);
		        $response->sendError(ResponseResultStatus::DATABASE_ERROR, '保存数据异常！');
		    } 
		}		    
        $response->sendResult('ok');
        return $response;
	}
	/**
	 * 美粒宝典:删除/发布
	 * @date: 2016年1月4日 
	 * @author: chenxiaolin
	 */
	public function setStateAction(){
		$req=$this->request;
		$id=$req->getQuery("id");
		$state=$req->getQuery("state");
		if(!in_array($state, [1,3])){
		    $arr=array(
		        "status"=>0,
		        "errmsg"=>"参数错误"
		    );
		}
		$canon = CosBeautyCanon::findFirst("id = $id");
	    if(!$canon) {
	        $arr=array(
	            "status"=>0,
	            "errmsg"=>"美粒宝典不存在"
	        );
        }
        //2.0.1新增需求：发布时将添加时间修改为当前时间
        if($state == 1){//发布
            $canon->update([
                'state' => $state,
                'settime' => date("Y-m-d H:i:s")
            ]);
        }else{//删除
            $canon->update(['state' => $state]);
        } 
	    
		$arr=array(
			"status"=>10000
		);
		echo json_encode($arr);
	}
	/**
	 * 首页推荐美粒宝典1.0版本
	 *
	 * @return $this|ResponseResult
	 */
	public function recommendAction(){
		$req=$this->request;
		if(!$req->isPost()) {
			$this->view->setVar('id',$req->getQuery("id"));
			$this->view->setVar('openCity', $this->openCityList());
			return;
		}
		$cityid=$req->getPost("cityid");
		$sort=$req->getPost("sort");
		$canon_id=$req->getPost("id");
		$model=new CosPointCanon();
		$info=$model->find("open_city_id = $cityid and sort = $sort")->toArray();
		if(count($info)!=0){
			$arr=array(
				"status"=>0,
			);
			echo json_encode($arr);
			exit;
		}
		$model->canon_id=$canon_id;
		$model->sort=$sort;
		$model->open_city_id=$cityid;
		$model->save();
		$query=new CosBeautyCanon();
		$cosbeautycanon=$query->findFirst("id = ".$canon_id);
		$cosbeautycanon->state=2;
		$flg=$cosbeautycanon->save();
		$arr=array(
			"status"=>1,
		);
		echo json_encode($arr);
		exit;
	}
	/**
	 * 首页推荐美粒宝典取消推荐1.0版本
	 *
	 * @return $this|ResponseResult
	 */
	public function undoAction(){
		$req=$this->request;
		$id=$req->getQuery("id");
		$status=CosPointCanon::find("canon_id = $id")->delete();
		$cosbeautycanon=CosBeautyCanon::findFirst("id = $id");
		$cosbeautycanon->state=1;
		$flg=$cosbeautycanon->save();
		if($flg==true && $status==true){
			$arr=array(
				"status"=>10000
			);
			echo json_encode($arr);
			exit;
		}else{
			$arr=array(
					"status"=>0,
					"errmsg"=>"error"
			);
			echo json_encode($arr);
			exit;
		}
	}
	public function testsAction(){
		$jpush=new Jpush();
		$param['type'] =1;
		$param['ispushservice']=1;
		$param['phone'] ='18623640927';
		$param['content'] ="HAHHA";
		$jpush->setval($param);
		$a=$jpush->push();
		var_dump($a);
		exit;
		
	}
	
	
}